var currTeam, currPrice;
var scores = [0, 0, 0];
var prices = [100, 200, 300, 500, 800];

function $(id)
{
	return document.getElementById(id);
}

function fillCells()
{
	var tbody = $("questions_table").tBodies[0];
	for (var i = 0; i < tbody.rows.length; i++)
	{
		for (var j = 1; j < tbody.rows[i].cells.length; j++)
		{
			var cell = tbody.rows[i].cells[j];
			cell.id = "c" + i + (j -1);

			for (var x in cell.childNodes)
			{
				if (cell.childNodes[x].className == "question_number")
				{
					cell.childNodes[x].innerHTML = j;
					continue;
				}
				if (cell.childNodes[x].className == "question_cost")
				{
					cell.childNodes[x].innerHTML = prices[j-1];
				}
			}
		}
	}
}

function bindOnClick()
{
	$("questions_table").onclick = function(e)
	{
		var event = (e ? e : window.event);
		var target = (event.target ? event.target : event.srcElement);
		var i = new Number(target.parentNode.id.charAt(1));
		var j = new Number(target.parentNode.id.charAt(2));
		target.parentNode.innerHTML = "";
		askQuestion(i, j);
	}
	
	$("player_button_1").onclick = function(e)
	{
		currTeam = 0;
	}
	
	$("player_button_2").onclick = function(e)
	{
		currTeam = 1;
	}
	
	$("player_button_3").onclick = function(e)
	{
		currTeam = 2;
	}
	
	$("yes_button").onclick = function(e)
	{
		if (currTeam == -1)
		{
			alert("Error with currTeam");
			return;
		}
		if (currPrice == -1)
		{
			alert("Error with currPrice");
			return;
		}
		scores[currTeam] += currPrice;
		currTeam = currPrice = -1;
		updateScores();
		switchToMain();
	}
	
	$("no_button").onclick = function(e)
	{
		if (currTeam == -1)
		{
			alert("Error with currTeam");
			return;
		}
		if (currPrice == -1)
		{
			alert("Error with currPrice");
			return;
		}
		scores[currTeam] -= currPrice;
		currTeam = currPrice = -1;
		updateScores();		
		switchToMain();
	}
}

function updateScores()
{
	for (var i = 0; i < 3; i++)
	{
		var id = "player_button_" + (i+1);
		var childs = $(id).childNodes;
		for (var j = 0; j < childs.length; j++)
		{
			if (childs[j].className == "player_score")
			{
				childs[j].innerHTML = scores[i];
				break;
			}
		}
	}
}

function switchToQuestion()
{
	$("main_screen").style.visibility = "hidden";
	$("question_screen").style.visibility = "visible";
}

function switchToMain()
{
	$("main_screen").style.visibility = "visible";
	$("question_screen").style.visibility = "hidden";
}

function askQuestion(i, j)
{
	var question = questions[i][j];
	currPrice = prices[j];
	displayQuestion(question);
}

function displayQuestion(q)
{
	addQuestionContent(q);
	switchToQuestion();
}

function addQuestionContent(q)
{
	if (q.type == "text")
	{
		$("question_text").innerHTML = q.data;
	}
}

window.onload = function()
{
	fillCells();
	bindOnClick();
	updateScores();
}
